package com.efounder.agency.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.activity.TabBottomActivity;
import com.efounder.activity.TabBottomActivity.TabBottomActivityResultListener;
import com.efounder.chat.adapter.TaskListAdapter;
import com.efounder.chat.event.PendingTaskListSizeEvent;
import com.efounder.chat.event.ProcessedTaskListSizeEvent;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.model.Task;
import com.efounder.chat.model.TaskRefreshEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.ospmobilelib.R;
import com.efounder.pansoft.chat.record.voice.DensityUtil;
import com.efounder.util.AppContext;
import com.efounder.util.SetFMTEnvironmetVariableValueUtil;
import com.pansoft.xmlparse.FormatCol;
import com.pansoft.xmlparse.FormatRow;
import com.pansoft.xmlparse.FormatSet;
import com.pansoft.xmlparse.FormatTable;
import com.pansoft.xmlparse.MobileFormatUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.qqtheme.framework.util.ScreenUtils;


/**
 * 待办 最新
 *
 * @author long 2015年9月2日13:56:45
 */
@SuppressLint({"InflateParams", "HandlerLeak"})
public class AgentFgNew extends BaseFragment implements TabBottomActivityResultListener {
    private static final String TAG = "AgentFgNew";
    private static final String resPath = AppConstant.APP_ROOT + "/res/unzip_res/Image/";
    // TODO: 17-8-14 共享用下面的链接
    private static final String URL1 = EnvironmentVariable.getProperty("OSPTaskURL", "http://11.11.48.10:10006/BIZPortalServer") + "/OpenAPIService/TJFlowTask?RequestParam=";
    private static final String Product = EnvironmentVariable.getProperty("Product", "BusinessService");
    private static final String LoadType = EnvironmentVariable.getProperty("LoadType", "USER2LIST");
    //共享的不分页
//    private String URL2 = "{Param:{Product:'BusinessService',RESR_STATUS:'all',LoadType='USER2LIST'";
    private String URL2 = "{Param:{Product:'" + Product + "',RESR_STATUS:'all',LoadType='" + LoadType + "'";
    //共享不分页
    private static String URL3 = ",UserName='" + EnvironmentVariable.getUserName() + "'}}";

    private static final int UPDATED = 1;
    private RecyclerView mRecyclerView;
    private boolean hasLoadData = false;
    private int page = 1;//加载任务的页码
    private List<Task> mData;
    private FormatSet formatSet;
    TaskListAdapter adapter;
    RelativeLayout include;
    ScrollView linearLayout;
    private SmartRefreshLayout mSrl;
    private StubObject stubObject;

    private int taskDataItem0, taskDataItem1;//中油铁工的角标
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            getTaskData(false);
        }
    };
    private String status;
    private ImageView mNetErrorView;
    private String addwhere;
    private String addwhereProcessed;
    private String addwherePending;
    private String userName;

    public AgentFgNew() {
        super();
    }

    public static AgentFgNew newInstance(boolean b, String status, StubObject stubObject) {
        AgentFgNew agentFgNew = new AgentFgNew();
        Bundle bundle = new Bundle();
        bundle.putString("RESR_STATUS", status);
        bundle.putBoolean("IS_ALONE", b);
        bundle.putSerializable("stubObject", stubObject);
        agentFgNew.setArguments(bundle);
        return agentFgNew;
    }

    public AgentFgNew(StubObject _stubObject) {
        super();
        stubObject = _stubObject;
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof TabBottomActivity) {
            TabBottomActivity tabBottomActivity = (TabBottomActivity) activity;
            tabBottomActivity.setOnTabBottomActivityResultListener(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//		if (isAlone() && !hasLoadData) {
//			new NewLoadAsyncTask().execute();
//		}
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//        String userId = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
        userName = EnvironmentVariable.getUserName();
        if (null != getArguments()) {
            status = getArguments().getString("RESR_STATUS");
            boolean is_alone = getArguments().getBoolean("IS_ALONE");
            setAlone(is_alone);
            StubObject stubObject = (StubObject) getArguments().getSerializable("stubObject");
            addwhereProcessed = stubObject.getString("ADDWHERE_PROCESSED", "");
            addwherePending = stubObject.getString("ADDWHERE_PENDING", "");

            URL2 = "{Param:{Product:'" + Product + "',RESR_STATUS:'" + status + "',LoadType='" + LoadType + "'";
        }

        View root = inflater.inflate(R.layout.fg_new_agent_ui_withtilte, null);

        mSrl = (SmartRefreshLayout) root
                .findViewById(R.id.srl);
        // pullToRefreshScrollView.setOnRefreshListener(this);
        //只允许下拉
        // pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        mSrl.setEnableLoadMore(false);
        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getTaskData(false);
            }
        });
        include = (RelativeLayout) root.findViewById(R.id.include);
        // 判断fragment是否是单独的
        if (isAlone()) {
            include.setVisibility(View.VISIBLE);
        } else {
            include.setVisibility(View.GONE);
        }
        mNetErrorView = root.findViewById(R.id.agentfg_net_error);
        ViewGroup.LayoutParams layoutParams = mNetErrorView.getLayoutParams();
        /**
         * 获取状态栏高度——方法1
         * */
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        layoutParams.height = ScreenUtils.heightPixels(getContext()) - DensityUtil.dp2px(160) - statusBarHeight1;
        mNetErrorView.setLayoutParams(layoutParams);
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        TextView title = (TextView) root.findViewById(R.id.fragmenttitle);
        title.setText("任务中心");
        LinearLayout leftbacklayout = (LinearLayout) root
                .findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);
        leftbacklayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//				AgentFgNew.this.getFragmentManager().popBackStack();
                getActivity().finish();
            }
        });
        formatSet = MobileFormatUtil.getInstance().getFormatSet();

        mData = new ArrayList<>();
        //在每次这个页面第一次加载的时候，需要将badgeNum设为0，防止网络问题加载不出数据，但是badgeNum还是之前数据的问题
        caculateBadgeNum(0 + "");
        getTaskData(false);
        Button buttonRight = (Button) root.findViewById(R.id.closeButton);
        buttonRight.setVisibility(View.INVISIBLE);
        buttonRight.setBackgroundResource(R.drawable.rightmenu);
        buttonRight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });
        linearLayout = (ScrollView) root
                .findViewById(R.id.fg_new_agent_linear_layout);

        mRecyclerView = (RecyclerView) root.findViewById(R.id.recyclerView);

        super.onCreateView(inflater, container, savedInstanceState);
        adapter = new TaskListAdapter(getActivity(), mData);
        adapter.setStatus(status);
        adapter.setOnItemClickLitener(new TaskListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("TaskDetail_FLOW_ID", null);
                map.put("task_flowId", mData.get(position).getFlow_id());
                map.put("task_header", mData.get(position).getTitle());
                map.put("task_avatar", "");
                map.put("task_badgeValue", String.valueOf(mData.get(position).getTodoNum()));
                if (status.equals("processed")) {
                    map.put("ADDWHERE", addwhereProcessed);
                } else {
                    map.put("ADDWHERE", addwherePending);

                }

//                EnvironmentVariable.setPowerMap(map);
                try {
                    Map<String, Object> fmtMap = SetFMTEnvironmetVariableValueUtil.setFmtEnvironmentValue(getContext(), mData.get(position).getFlow_id());
                    map.putAll(fmtMap);
                    if (map.get("hfmt") == null) {
                        Toast.makeText(getContext(), "此条在Mobile_FMT中未配置，请联系管理员", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Intent intent = new Intent(getActivity(), Class.forName("com.efounder.RNTaskActivity"));
                    intent.putExtra("status", status);
                    intent.putExtra("args", (Serializable) map);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        mRecyclerView.setAdapter(adapter);
        return root;

    }

    /**
     * 计算角标
     *
     * @param s1
     */
    private void caculateBadgeNum(String s1) {
        if (null != status) {
            //todo 20181029 yqs,角标存储env 是因为计算总数的需要，通过 event事件刷新
            if (status.equals("processed")) {
                EnvironmentVariable.setProperty("Badge_Task_Processed", s1);
            } else {
                EnvironmentVariable.setProperty("Badge_Task_Pending", s1);
            }
        }
        EventBus.getDefault().post(new UpdateBadgeViewEvent(BadgeUtil.CHAT_ID_TASK + "", (byte) 2));


        //石油部分为了兼容之前的，发送待办数量刷新的事件
        if ("pending".equals(status)) {
            //如果是待办
            try {
                BadgeUtil.CHAT_ID_TASK_DB_COUNT = Integer.valueOf(s1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        EventBus.getDefault().post(new UpdateBadgeViewEvent(BadgeUtil.CHAT_ID_TASK_DB + "", (byte) 2));
    }

    /**
     * @param fmt
     * @return
     */
    public static Map getFMT(FormatTable fmt) {

        final Map<String, Object> hfmt = new HashMap<>();

        List<FormatRow> rows = fmt.getFormatRowList();
        List<List> colsList = new ArrayList<List>();
        for (int i = 0; i < rows.size(); i++) {
            List<FormatCol> cols = rows.get(i).getList();
            List<Map> colArray = new ArrayList<Map>();

            for (int j = 0; j < cols.size(); j++) {
                Map<String, Object> colum = new HashMap<String, Object>();
                colum.put("caption", cols.get(j).getCaption());
                colum.put("dataSetColID", cols.get(j).getDataSetColID());
                colum.put("columnType", cols.get(j).getColumnType());
                colum.put("numberPrecision", cols.get(j).getNumberPrecision());
                colum.put("textAlign", cols.get(j).getTextAlign());
                colum.put("textFormat", cols.get(j).getTextFormat());
                colum.put("dateFormat", cols.get(j).getDateFormat());
                colum.put("mask", cols.get(j).getMask());

                colArray.add(colum);
            }
            colsList.add(colArray);
        }

        hfmt.put("detailCol", fmt.getDetailCol());
        hfmt.put("detailName", fmt.getDetailName());
        hfmt.put("rows", rows.size());
        hfmt.put("cols", colsList);
        return hfmt;
    }

    /**
     * 请求数据
     *
     * @param paging true表示分页加载，false为刷新
     */
    private void getTaskData(final boolean paging) {
        Log.d("getTaskData", "begin-->");
        EFHttpRequest httpRequest = new EFHttpRequest(AppContext.getInstance().getApplicationContext());
        httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {
            @Override
            public void onRequestSuccess(int requestCode, String response) {
                mNetErrorView.setVisibility(View.GONE);
                linearLayout.setVisibility(View.VISIBLE);
                if (response.equals("")) {
                    caculateBadgeNum(getBadgeNum() + "");
                    mSrl.finishRefresh();
                    mSrl.finishLoadMore();
                } else {
                    try {
                        if (!paging) {
                            mData.clear();
                        }
                        JSONObject responseObject = new JSONObject(response);
                        JSONArray taskListArray = responseObject.getJSONArray("TaskList");
                        if (taskListArray != null) {
                            for (int i = 0; i < taskListArray.length(); i++) {
                                Task task = new Task();
                                task.setTitle((taskListArray.getJSONObject(i).getString("FLOW_MC")));
                                task.setIcon((taskListArray.getJSONObject(i).getString("FlowIcon")));
                                try {
                                    task.setInfo((taskListArray.getJSONObject(i).getString("FLOW_DES")));
                                } catch (JSONException e) {
                                    task.setInfo("");
                                }
                                String PFLOW_ID = taskListArray.getJSONObject(i).optString("PFLOW_ID");
                                if (PFLOW_ID != null && !PFLOW_ID.equals("")) {
                                    task.setId(PFLOW_ID);
                                } else {
                                    task.setId(taskListArray.getJSONObject(i).getString("FLOW_ID"));
                                }
                                task.setFlow_id(taskListArray.getJSONObject(i).getString("FLOW_ID"));
                                if (null != status) {
                                    if (status.equals("processed")) {
                                        task.setTodoNum((taskListArray.getJSONObject(i).getInt("TASK_PROCESSED_COUNT")));

                                    } else {
                                        task.setTodoNum((taskListArray.getJSONObject(i).getInt("TASK_PENDING_COUNT")));

                                    }
                                }
                                task.setStatus(status);
//                                task.setTodoNum((taskListArray.getJSONObject(i).getInt("TASK_PENDING_COUNT")));
                                mData.add(task);
                            }
                        }
                        adapter.notifyDataSetChanged();
                        caculateBadgeNum(getBadgeNum() + "");
                        mSrl.finishRefresh();
                        mSrl.finishLoadMore();
                    } catch (JSONException e) {
                        e.printStackTrace();
                        //ToastUtil.showToast(getActivity(), "没有更多数据了");
                        mSrl.finishRefresh();
                        mSrl.finishLoadMore();
                    }
                }
            }

            @Override
            public void onRequestFail(int requestCode, String message) {
                if (EnvironmentVariable.getProperty("APPID", "").equals("OSPMobileLiveApp")) {
                    //联信暂时没有任务
                    mNetErrorView.setVisibility(View.GONE);
                } else {
                    mNetErrorView.setVisibility(View.VISIBLE);
                }
                linearLayout.setVisibility(View.GONE);
                mData.clear();
                adapter.notifyDataSetChanged();
                caculateBadgeNum(getBadgeNum() + "");
                mSrl.finishRefresh();
                mSrl.finishLoadMore();
            }
        });
        /**
         * 共享不分页加载
         * */

        if ("".equals(addwhereProcessed) || "".equals(addwherePending) || null == addwhereProcessed || null == addwherePending) {

        } else {
            addwherePending = addwherePending.replaceAll("#id#", userName);

            if ("processed".equals(status)) {
                URL3 = ",UserName='" + EnvironmentVariable.getUserName() + "',FilterLastTask:'1',ADDWHERE:\"" + addwhereProcessed + "\"}}";
            } else {
                URL3 = ",UserName='" + EnvironmentVariable.getUserName() + "',ADDWHERE:\"" + addwherePending + "\"}}";

            }
        }

        String url = URL2 + URL3;
        url = URLEncoder.encode(url);
        httpRequest.httpGet(URL1 + url);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onSolveEventMessage(TaskRefreshEvent event) {
        getTaskData(false);
        //getTGBadgeNum();//中铁工专用，其他请注释掉
    }

    /**
     * 获取TG的报销和OA的角标数
     */
    private void getTGBadgeNum() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String className = "sy.petrochina.zsytg.utils.JExterInterface";
                    ClassLoader loader = Thread.currentThread().getContextClassLoader();
                    Class<?> clazz = loader.loadClass(className);
                    Method method = clazz.getMethod("getTodoCountForApp");
                    String ob = (String) method.invoke(clazz.newInstance(), new Object[]{});
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(ob);
                    if (jsonObject.getJSONObject("TaskDataItem0").getString("COUNT_ROW") != null &&
                            !jsonObject.getJSONObject("TaskDataItem0").getString("COUNT_ROW").equals("")) {
                        taskDataItem0 = Integer.valueOf(jsonObject.getJSONObject("TaskDataItem0").getString("COUNT_ROW"));
                        taskDataItem1 = Integer.valueOf(jsonObject.getJSONObject("TaskDataItem1").getString("COUNT_ROW"));
                        Log.d("wwl_test", "获取铁工角标完成");
                    }
                    handler.sendEmptyMessage(0);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (java.lang.InstantiationException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取总的角标数量
     *
     * @return 角标数
     */
    private int getBadgeNum() {
        if ("pending".equals(status)) {
            EventBus.getDefault().post(new PendingTaskListSizeEvent(mData.size(), mData));
        } else {
            EventBus.getDefault().post(new ProcessedTaskListSizeEvent(mData.size(), mData));
        }
        int badgeNum = 0;
        for (int i = 0; i < mData.size(); i++) {
            badgeNum += mData.get(i).getTodoNum();
        }
        return badgeNum;
    }

    @Override
    public void onVisible() {
        if (!hasLoadData) {
            linearLayout.setBackgroundResource(R.drawable.write);
        }
    }

    @Override
    public void onTabBottomActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("", "-------onTabBottomActivityResult:" + TAG);
        if (resultCode == Activity.RESULT_OK) {
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
